package com.eh.erd.oss.controller.api;

import com.eh.common.exception.BusinessException;
import com.eh.common.result.R;
import com.eh.common.result.ResponseEnum;
import com.eh.erd.oss.service.FileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

/**
 * @author zhuyuanwei
 * @version 1.0
 * @date 2021/5/13 11:18
 */
@Api(tags = "阿里云文件管理")
@RestController
@RequestMapping("/api/oss/file")
@Slf4j
public class FileController {

    @Autowired
    private FileService fileService;

    @ApiOperation("上传文件")
    @PostMapping("/upload")
    public R upload(@ApiParam(value = "文件",required = true)
                        @RequestParam("file") MultipartFile file,
                    @ApiParam(value = "模块",required = true) @RequestParam("module") String module){
        try {
            InputStream inputStream=file.getInputStream();
            String fileName=file.getOriginalFilename();
            String uploadUrl = fileService.upload(inputStream, module, fileName);
            return R.ok().message("上传成功").data("url",uploadUrl);
        } catch (IOException e) {
            throw new BusinessException(ResponseEnum.UPLOAD_ERROR,e);
        }
    }

    @ApiOperation("删除文件")
    @PostMapping("/remove")
    public R remove(@ApiParam(value = "文件地址",required = true)
                        @RequestParam("url") String url){
        fileService.removeFile(url);
        return R.ok().message("文件删除成功");
    }

}
